<template>
    <div class="learningexchange" style="">
        <div style="margin-bottom: 10px">
            <el-input v-model="text" @keyup.enter.native="getlearningExchanges" style="width: 200px" size="small">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
            <el-button @click="add" type="primary" size="mini" style="margin-left: 8px;">新增</el-button>
        </div>
        <el-table :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
            style="width: 100%" border>
            <el-table-column label="id" prop="postId" width="60">
            </el-table-column>
            <el-table-column label="帖子标题" prop="title" width="120">
            </el-table-column>
            <el-table-column label="帖子内容" prop="content" width="400">
            </el-table-column>
            <el-table-column label="帖子作者" prop="authorName" width="120">
            </el-table-column>
            <el-table-column label="点赞数量" prop="numberLikes" width="100">
            </el-table-column>
            <el-table-column label="帖子图片路径" prop="postImg" width="120">
            </el-table-column>
            <el-table-column label="帖子类型" prop="postName" width="100">
            </el-table-column>
            <el-table-column label="创建时间" prop="postDate" width="160">
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="page" style="display: flex;justify-content: center;" v-show="pageShow">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page.sync="currentPage" :page-size="pageSize" :page-sizes="[3, 6, 9, 12]"
                layout="total, prev, pager, next" :total="total">
            </el-pagination>
        </div>

        <!-- 弹窗   -->
        <el-dialog title="学习交流" :visible.sync="dialogFormVisible" width="30%" :close-on-click-modal="false">
            <el-form :model="entity">
                <el-form-item label="帖子名称" label-width="150px">
                    <el-input v-model="entity.title" autocomplete="off" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="帖子内容" label-width="150px">
                    <el-input type="textarea" v-model="entity.content" autocomplete="off" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="点赞数量" label-width="150px">
                    <el-input v-model="entity.numberLikes" autocomplete="off" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="帖子类型" label-width="150px" v-show="entity.postType ">
                    <el-select v-model="postTypeName" placeholder="请选择" style="width: 80%" @change="handleChange">
                        <el-option v-for="item in postSections" :key="item.id" :label="item.typeName"
                            :value="item.typeCode"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="图片" label-width="150px">
                    <el-upload action="http://localhost:9001/api/file/upload" multiple :on-success="handleSuccess"
                        ref="upload">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

import API from "@/api/request";

export default {
    inject: ['reload'],
    data() {
        return {
            tableData: [],
            search: '',
            //数据总数
            total: 0,
            //当前页
            currentPage: 1,
            //每页数量
            pageSize: 3,
            //控制分页显示
            pageShow: false,
            dialogFormVisible: false,
            entity: {},
            postSections: [],
            imgurl: '',
            user: {},
            postTypeName: '',
            text: ''
        }
    },
    methods: {
        handleChange(value) {
            // 选中值时更新 postTypeName 的值
            this.postTypeName = value;
        },
        handleEdit(index, row) {
            console.log(index, row);
            this.entity = JSON.parse(JSON.stringify(row))
            console.log(this.entity)
            // this.selectedTypeName();
            this.$nextTick(() => {
                if (this.$refs['upload']) {
                    this.$refs['upload'].clearFiles()
                }
            })
            this.dialogFormVisible = true;
        },
        handleDelete(index, row) {
            console.log(row)
            API.delete("/api/learningExchange/" + row.postId).then(res => {
                if (res.data.code === 200) {
                    this.$message.success("操作成功!");
                } else {
                    this.$message.error("操作失败!");
                    console.error("API 请求失败", res);
                }
                this.reload();
            }).catch(error => {
                console.error("API 请求错误", error);
            });
        },
        handleSuccess(res) {
            console.log(res)
            //修改图片路径
            this.imgurl = res.data;
            console.log("图片" + this.imgurl)
        },

        getlearningExchanges() {
            API.get("/api/learningExchange/pageList", {
                params: {
                    pageNum: this.currentPage,
                    pageSize: this.pageSize,
                    name: this.text
                }
            }).then(res => {
                if (res.data.code === 200) {
                    this.tableData = res.data.data.records;
                    this.total = res.data.data.total;
                    this.currentPage = res.data.data.current;
                    if (this.total > 0) {
                        this.pageShow = true;
                    }

                } else {
                    console.error("API 请求失败", res);
                }
            }).catch(error => {
                console.error("API 请求错误", error);
            });
        },
        //控制页数的函数
        handleSizeChange(val) {
            this.pageSize = val;
            console.log(`每页 ${val} 条`);
            this.getlearningExchanges();

        },
        // 控制页码的函数
        handleCurrentChange(val) {
            this.currentPage = val;
            console.log("查看当前页" + this.currentPage);
            console.log(`当前 ${val} 页`);
            this.getlearningExchanges();
        },
        save() {
            //如果有id则是修改操作，没有则为新增
            if (!this.entity.postId) {
                console.log("当前为空白")
                API.post("/api/learningExchange/add", {
                    "id": null,
                    "name": this.entity.title,
                    "content": this.entity.content,
                    "postImage": this.imgurl != "" ? this.imgurl : this.entity.postImg,
                    "type": 2,
                    "author": this.user.studentId,
                    "numberLikes": this.entity.numberLikes
                }).then(res => {
                    if (res.data.code === 200) {
                        this.$message.success("操作成功!");
                        this.dialogFormVisible = false;

                    } else {
                        console.error("API 请求失败", res);
                    }
                    this.reload();
                }).catch(error => {
                    console.error("API 请求错误", error);
                });
            } else {
                console.log("修改");
                API.put("/api/learningExchange/update", {
                    "id": this.entity.postId,
                    "name": this.entity.title,
                    "content": this.entity.content,
                    "postImage": this.imgurl != "" ? this.imgurl : this.entity.postImg,
                    "type": this.postTypeName,
                    "numberLikes": this.entity.numberLikes
                }).then(res => {
                    if (res.data.code === 200) {
                        this.$message.success("操作成功!");
                        this.dialogFormVisible = false;
                        this.reload()
                    } else {
                        console.error("API 请求失败", res);
                    }
                }).catch(error => {
                    console.error("API 请求错误", error);
                });
            }
        },
        //新增
        add() {
            this.dialogFormVisible = true;
            //清空对象
            this.entity = {}
            console.log("这是对象")
            console.log(JSON.stringify(this.entity))
            // API.post("/api/learningExchange/add", {
            //     "name": this.entity.title,
            //     "content": this.entity.content,
            //     "author": this.user.studentId,
            //     "postImage": this.imgurl != "" ? this.imgurl : "",
            //     "type": this.entity.postName,
            // }).then(res => {
            //     if (res.data.code === 200) {
            //         console.log(res)

            //     } else {
            //         console.error("API 请求失败", res);
            //     }
            // }).catch(error => {
            //     console.error("API 请求错误", error);
            // });

        },
        //获取分类
        getpostsectiones() {
            API.get("/api/postSection/list").then(res => {
                if (res.data.code === 200) {
                    this.postSections = res.data.data;
                    console.log(this.postSections)

                } else {
                    console.error("API 请求失败", res);
                }
            }).catch(error => {
                console.error("API 请求错误", error);
            });
        },
        // //设置分类名称
        // selectedTypeName() {
        //     console.log(this.postSections);

        //     // 使用 find 来找到匹配的项
        //     const selectedItem = this.postSections.find(item => {
        //         // 返回是否符合条件
        //         return item.typeCode == this.entity.postType;
        //     });

        //     console.log(selectedItem);

        //     this.postTypeName = selectedItem.typeName
        // }

    },
    // computed: {
    //     // 根据 postTypeName 查找对应的分类名称
    //     selectedTypeName() {
    //         const selectedItem = this.postSections.find(item => item.typeCode === this.entity.postType);
    //         console.log("查找后的"+selectedItem);
    //         return selectedItem ? this.postTypeName=selectedItem.typeName : ''; // 如果找不到对应项，返回空字符串
    //     }
    // },

    created() {
        this.getlearningExchanges();
        this.getpostsectiones();
        this.user = sessionStorage.getItem('user') ? JSON.parse(sessionStorage.getItem('user')) : {}
        console.log(this.user)
    }
}
</script>
<style>
.learningexchange {
    padding: 20px;
}
</style>